package com.kkkkkba.search.service.impl;

import com.kkkkkba.search.common.ErrorCode;
import com.kkkkkba.search.exception.BusinessException;
import com.kkkkkba.search.model.vo.MusicDetailsVo;
import com.kkkkkba.search.service.MusicService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 音乐服务实现类
 */
@Service
@Slf4j
public class MusicServiceImpl implements MusicService {

    private static final String subpageUrl_1 = "https://www.gequbao.com";
    private static final String subpageUrl_2 = "https://www.gequbao.com";

    @Override
    public MusicDetailsVo getMusicVo(long id, HttpServletRequest request) {
        MusicDetailsVo musicDetails = new MusicDetailsVo();
        String url = subpageUrl_2+ String.format("/music/%s", id);
        Document doc = null;
        Elements newsHeadlines = null;
        try {
            doc = Jsoup.connect(url).get();
//            System.out.println(doc);
            Element script = doc.select("script").get(4);
//            System.out.println(script.toString());
            // 提取歌名
            Pattern songNamePattern = Pattern.compile("name: '(.*?)'");
            Matcher songNameMatcher = songNamePattern.matcher(script.toString());
            if (songNameMatcher.find()) {
                String songName = songNameMatcher.group(1);
                musicDetails.setName(songName);
            }

            // 提取歌手
            Pattern singerPattern = Pattern.compile("artist: '(.*?)'");
            Matcher singerMatcher = singerPattern.matcher(script.toString());
            if (singerMatcher.find()) {
                String singer = singerMatcher.group(1);
                musicDetails.setName(musicDetails.getName() + "-" + singer);
            }

            // 提取封面
            Pattern coverPattern = Pattern.compile("cover: '(.*?)'");
            Matcher coverMatcher = coverPattern.matcher(script.toString());
            if (coverMatcher.find()) {
                String coverUrl = coverMatcher.group(1);
                musicDetails.setCover(coverUrl);

            }

            // 提取歌词
            Pattern lrcPattern = Pattern.compile("lrc: '(.*?)'");
            Matcher lrcMatcher = lrcPattern.matcher(script.toString());
            if (lrcMatcher.find()) {
                String lrc = lrcMatcher.group(1);
                musicDetails.setLrc(lrc.replace("\"", ""));

            }

            musicDetails.setUrl("https://www.gequbao.com/api/play_url?id=" + id);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "NOT_FOUND_ERROR");
        }
//        System.out.println(musicDetails);
        return musicDetails;
    }
}

